package com.plusjun.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.plusjun.cart.feign.ProductFeignService;
import com.plusjun.cart.interceptor.CartInterceptor;
import com.plusjun.cart.service.CartService;
import com.plusjun.cart.to.UserInfoTO;
import com.plusjun.cart.vo.Cart;
import com.plusjun.cart.vo.CartItem;
import com.plusjun.cart.vo.SkuInfoVO;
import com.plusjun.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    private final String CART_PREFIX = "gulimall:cart:";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        // 到redis中去差，看看有没有此商品
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();

            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1、远程查询要添加商品的信息
                R skuInfo = productFeignService.info(skuId);
                SkuInfoVO data = (SkuInfoVO) skuInfo.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                });
                // 2、添加新商品到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
                cartItem.setTitle(data.getSkuTitle());
            }, executor);


            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                // 3、远程查询sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuSaleAttrValuesTask, getSkuInfoTask).get();
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem item = JSON.parseObject(o, CartItem.class);
        return item;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 判断是否登录
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO.getUserId() != null) {
            // 1、已登录
            String cartKey = CART_PREFIX + userInfoTO.getUserId();
            // 1.1、如果临时购物车的数据还没有合并，则进行合并
            String tempCartKey = CART_PREFIX + userInfoTO.getUserKey();
            List<CartItem> tempCartItems = getCartItem(tempCartKey);
            if (tempCartItems != null) {
                // 1.2、临时购物车中有数据，需要合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 1.3、合并后需要清空临时购物车
                clearCart(tempCartKey);
            }

            // 1.3、获取登录后的购物车数据(包含合并来的临时购物车的数据，和登录后的购物车的数据）
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);

        } else {
            // 2、未登录
            String cartKey = CART_PREFIX + userInfoTO.getUserKey();
            // 2.1、获取临时购物车的所有购物项
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkitem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO.getUserId() == null) {
            return null;
        }
        String cartKey = CART_PREFIX + userInfoTO.getUserId();
        List<CartItem> cartItem = getCartItem(cartKey);
        List<CartItem> res = cartItem.stream().filter(item -> {
            return item.getCheck();
        }).collect(Collectors.toList());
        // 收集到所有购物车中所选中商品的skuId
        List<Long> skuIds = res.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());
        // 远程查询这些商品的价格,然后更新为最新价格

        R r = productFeignService.getPrice(skuIds);
        Map<Long, BigDecimal> price = new HashMap<>();
        if (r.getCode() == 0) {
            price = (Map<Long, BigDecimal>) r.getData("price", new TypeReference<Map<Long, BigDecimal>>() {
            });
        }
        Map<Long, BigDecimal> finalPrice = price;
        res = res.stream().map(item -> {
            for (Long skuId : finalPrice.keySet()) {
                if (skuId.equals(item.getSkuId())) {
                    item.setPrice(finalPrice.get(skuId));
                }
            }
            return item;
        }).collect(Collectors.toList());
        return res;

    }

    /**
     * 获取到要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1、获取用户信息
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        // 2、判断是临时购物车还是用户购物车
        String cartKey = "";
        if (userInfoTO.getUserId() != null) {
            // 用户已登录
            cartKey = CART_PREFIX + userInfoTO.getUserId();
        } else {
            // 离线购物车
            cartKey = CART_PREFIX + userInfoTO.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private List<CartItem> getCartItem(String cartKey) {
        BoundHashOperations<String, Object, Object> cartOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
